<?php

namespace seecms;

use magein\utils\Console;
use seecms\db\SeeDbException;
use seecms\lib\module\ModuleConfig;
use seecms\lib\module\ModulePublish;

/**
 * see发布类
 */
class SeePublish extends ModulePublish
{

    protected $silent = false;

    /**
     * 静默输出
     * @return $this
     */
    public function silent($silent = true): SeePublish
    {
        $this->silent = boolval($silent);

        return $this;
    }

    /**
     * 发布静态资源文件
     * @return bool
     */
    public function vendor(): bool
    {

        $target = See::config()->vendor->root() . 'vendor' . DIRECTORY_SEPARATOR;

        if (!class_exists('ZipArchive')) {
            return false;
        }

        $dir = dirname(see_root()) . '/static';

        $lib_path = $dir . '/lib.zip';
        $seecms_path = $dir . '/seecms.zip';

        $zip = new \ZipArchive();
        if (is_file($lib_path) && !is_dir($target . 'lib')) {
            if ($zip->open($lib_path) !== true) {
                return false;
            }
            // 解压到目标目录
            if (!$zip->extractTo($target)) {
                $zip->close();
                return false;
            }
            $zip->close();
        }

        if (is_file($seecms_path) && !is_dir($target . 'seecms')) {
            if ($zip->open($seecms_path) !== true) {
                return false;
            }
            // 解压到目标目录
            if (!$zip->extractTo($target)) {
                $zip->close();
                return false;
            }
            $zip->close();
        }

        return true;
    }

    /**
     * table文件路径地址
     * @return string
     */
    public function tableFile(): string
    {
        return dirname(__FILE__, 2) . '/database/table.sql';
    }


    /**
     * 创建用户
     * @return void
     * @throws SeeDbException
     */
    protected function createUser()
    {
        $data = See::db()->table('see_user')->where('username', 'root')->find();
        if (empty($data)) {
            $password = \seecms\lib\Auth::password('123456');
            See::db()->table('see_user')->insert(
                [
                    'username' => 'root',
                    'password' => $password,
                    'nickname' => 'seecms',
                    'avatar' => '',
                    'phone' => '18888888888',
                    'email' => 'root@seecms.com',
                    'tries' => 0,
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]
            );
        }

        $data = See::db()->table('see_user')->where('username', 'admin')->find();
        if (empty($data)) {
            $password = \seecms\lib\Auth::password('123456');
            See::db()->table('see_user')->insert(
                [
                    'username' => 'admin',
                    'password' => $password,
                    'nickname' => '管理员',
                    'avatar' => '',
                    'phone' => '18888888886',
                    'email' => 'admin@seecms.com',
                    'tries' => 0,
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]
            );
        }
    }

    protected function getMenuList(): array
    {
        return [
            $this->concatMenu('0', '用户管理', 'iconfont icon-user-settings-line', '', '20', '_iframe'),
            $this->concatMenu('1', '用户管理', 'iconfont icon-user-settings-line', 'userManager/index', '10', '_iframe'),
            $this->concatMenu('1', '角色管理', 'iconfont icon-user-shared-2-line', 'userRole/index', '20', '_iframe'),
            $this->concatMenu('1', '菜单管理', 'iconfont icon-other', 'userMenu/index', '30', '_iframe'),
            $this->concatMenu('1', '权限规则', 'iconfont icon-user-settings-line', 'userRule/index', '40', '_iframe'),
            $this->concatMenu('1', '权限申请', 'iconfont icon-unlock', 'userRuleApply/index', '50', '_iframe'),
            $this->concatMenu('1', '登录日志', 'iconfont icon-history', 'userLoginLog/index', '999', '_iframe'),
            $this->concatMenu('0', '常规管理', 'iconfont icon-setup', '', '10', '_iframe'),
            $this->concatMenu('8', '系统配置', 'iconfont icon-manage', 'general/setting', '100', '_iframe'),
            $this->concatMenu('8', '附件管理', 'iconfont icon-picture', 'attachment/index', '200', '_iframe'),
            $this->concatMenu('8', '数据库备份', 'iconfont icon-database-2-line', 'database/setting', '300', '_iframe'),
        ];
    }

    protected function createRole()
    {
        $table = function () {
            return See::db()->table('see_user_role');
        };

        $concat = function ($name, $description) {
            return [
                'name' => $name,
                'rule' => '',
                'menu' => '',
                'description' => $description,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
        };

        $data = $table()->where('name', '超级管理员')->find();
        if (empty($data)) {
            $table()->insert($concat('超级管理员', '拥有所以权限'));
        }

        $data = $table()->where('name', '管理员')->find();
        if (empty($data)) {
            $table()->insert($concat('管理员', '拥有基本的权限，用于分配菜单，审核权限申请等'));
        }
    }

    protected function getRuleList(): array
    {
        return [
            $this->concatRule('attachment', '附件列表', 'attachment/index'),
            $this->concatRule('attachment', '附件新增', 'attachment/create'),
            $this->concatRule('attachment', '附件保存', 'attachment/save'),
            $this->concatRule('attachment', '附件查看', 'attachment/read'),
            $this->concatRule('attachment', '附件编辑', 'attachment/edit'),
            $this->concatRule('attachment', '附件更新', 'attachment/update'),
            $this->concatRule('attachment', '附件删除', 'attachment/del'),
            $this->concatRule('user', '用户列表', 'userManager/index'),
            $this->concatRule('user', '用户新增', 'userManager/create'),
            $this->concatRule('user', '保存用户', 'userManager/save'),
            $this->concatRule('user', '用户授权', 'permission/userGrant'),
            $this->concatRule('user', '用户查看', 'userManager/read'),
            $this->concatRule('user', '用户编辑', 'userManager/edit'),
            $this->concatRule('user', '用户更新', 'userManager/update'),
            $this->concatRule('user', '用户删除', 'userManager/del'),
            $this->concatRule('user_role', '用户角色列表', 'userRole/index'),
            $this->concatRule('user_role', '用户角色创建', 'userRole/create'),
            $this->concatRule('user_role', '保存用户角色', 'userRole/save'),
            $this->concatRule('user_role', '角色授权页面', 'permission/roleGrant'),
            $this->concatRule('user_role', '用户角色edit', 'userRole/edit'),
            $this->concatRule('user_role', '更新用户角色', 'userRole/update'),
            $this->concatRule('user_role', '用户角色删除', 'userRole/del'),
            $this->concatRule('menu', '菜单列表', 'userMenu/index'),
            $this->concatRule('menu', '菜单新增页面', 'userMenu/create'),
            $this->concatRule('menu', '保存菜单', 'userMenu/save'),
            $this->concatRule('menu', '菜单查看', 'userMenu/read'),
            $this->concatRule('menu', '菜单编辑页面', 'userMenu/edit'),
            $this->concatRule('menu', '更新菜单', 'userMenu/update'),
            $this->concatRule('menu', '菜单删除', 'userMenu/del'),
            $this->concatRule('rule', '权限规则列表', 'userRule/index'),
            $this->concatRule('rule', '权限规则创建', 'userRule/create'),
            $this->concatRule('rule', '资源规则保存', 'userRule/save'),
            $this->concatRule('rule', '权限规则查看', 'userRule/read'),
            $this->concatRule('rule', '权限规则编辑', 'userRule/edit'),
            $this->concatRule('rule', '权限规则更新', 'userRule/update'),
            $this->concatRule('rule', '权限规则删除', 'userRule/del'),
            $this->concatRule('user_rule_apply', '权限申请列表', 'userRuleApply/index'),
            $this->concatRule('user_rule_apply', '权限申请审核', 'userRuleApply/edit'),
            $this->concatRule('user_rule_apply', '权限申请更新', 'userRuleApply/update'),
            $this->concatRule('user_login', '登录日志列表', 'userLogin/index'),
            $this->concatRule('database', '数据库备份', 'database/setting'),
            $this->concatRule('database', '备份日志', 'database/index'),
            $this->concatRule('database', '备份下载', 'database/download'),
            $this->concatRule('database', '执行备份', 'database/backup'),
            $this->concatRule('database', '备份发送到邮箱', 'database/send'),
            $this->concatRule('general', '常规配置页面展示', 'general/setting'),
            $this->concatRule('general', '常规配置保存', 'general/saveSetting'),
            $this->concatRule('general', '发送测试邮件', 'general/emailTest'),
            $this->concatRule('permission', '菜单管理', 'permission/menu'),
            $this->concatRule('permission', '保存菜单排序', 'permission/setMenuSort'),
            $this->concatRule('permission', '设置菜单状态', 'permission/setMenuStatus'),
            $this->concatRule('permission', '保存用户角色', 'permission/saveUserRoles'),
            $this->concatRule('permission', '保存用户菜单', 'permission/saveUserMenus'),
            $this->concatRule('permission', '保存用户权限', 'permission/saveUserRules'),
            $this->concatRule('permission', '保存角色菜单', 'permission/saveRoleMenus'),
            $this->concatRule('permission', '保存角色权限', 'permission/saveRoleRules'),
        ];
    }

    public function init()
    {
        !$this->silent && Console::green('  seecms发布静态资源文件');
        $this->vendor();
        !$this->silent && Console::green('  seecms创建数据库');
        $this->table();
        !$this->silent && Console::green('  seecms创建基础数据');
        $this->createUser();
        $this->createRole();
        $this->createMenu();
        $this->createRule();
    }

    /**
     * 模块发布
     * @throws \Throwable
     */
    public function module()
    {
        // 发布配置文件中的模块
        if ($modules = See::module()->get()) {

            foreach ($modules as $module) {
                if (class_exists($module)) {
                    $cla = new $module();
                    if ($cla instanceof ModuleConfig) {
                        $publish = $cla->publish();
                        if ($publish instanceof ModulePublish) {
                            !$this->silent && Console::green('  seecms发布模块:' . $module);
                            $publish->init();
                        }
                    }
                }
            }
        }
    }
}
